package test.hello.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SftpUtils {

	private static Session sshSession;
	private static ChannelSftp channelSftp;

	// 连接sftp
	public static ChannelSftp sftpConnection(String host, int port, String userName, String password) {
		JSch jsch = new JSch();
		try {
			sshSession = jsch.getSession(userName, host, port);
			sshSession.setPassword(password);
			Properties properties = new Properties();
			properties.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(properties);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			channelSftp = (ChannelSftp) channel;
		} catch (JSchException e) {
			e.printStackTrace();
		}
		return channelSftp;

	}

	public static void sftpClose(ChannelSftp channelSftp) {
		if (channelSftp != null) {
			if (channelSftp.isConnected()) {
				channelSftp.disconnect();
			}
		}
	}

	public static void sessionClose() {
		if (sshSession != null) {
			if (sshSession.isConnected()) {
				sshSession.disconnect();
				sshSession = null;
			}
		}
	}

	public static void uploadFile(ChannelSftp channelSftp, String filePath, String uploadPath, String fileName)
			throws SftpException, FileNotFoundException {
		try {
			channelSftp.cd(uploadPath);
			channelSftp.pwd();
		} catch (SftpException e) {
			String [] dirs = uploadPath.split("/");
			for(String dir :dirs ) {
				if (dir == null || "".equals(dir)) continue;
					channelSftp.mkdir(dir);
					channelSftp.cd(dir);
			}
		}
		File file = new File(filePath);
		InputStream stream = new FileInputStream(file);
		channelSftp.put(stream, fileName);

	}
	
	public static void downloadFile(ChannelSftp channelSftp,String sftpPath,String downPath) throws IOException, SftpException {
		File file =new File(downPath);
		OutputStream outStream = new FileOutputStream(file);
		channelSftp.get(sftpPath, outStream);
	}

	public static void main(String[] args) throws Exception {	
		ChannelSftp channelSftp = SftpUtils.sftpConnection("47.93.30.147", 22, "myftp", "ftp123");
		uploadFile(channelSftp,"D:\\ss.txt","/home/myftp","ss.txt");
		sessionClose();
		sftpClose(channelSftp);

	}
}